package 多线程初阶.示例测试;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 通过标准库的阻塞队列实现生产者消费者模型
 */
public class TestDemo19 {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> blockingQueue=new LinkedBlockingDeque<>();
        Thread customer=new Thread(()->{
            while (true){
                try {
                    int value=blockingQueue.take();
                    Thread.sleep(1000);
                    System.out.println("消费元素:"+value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者");
        customer.start();
        Thread producer=new Thread(()->{
            Random random=new Random();
            while (true){
               int value=random.nextInt(1000);
                try {
                    blockingQueue.put(value);
                    System.out.println("生产元素:"+value);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        producer.start();
        customer.join();
        producer.join();
    }
}
